package com.jiguiquan.www.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiguiquan.starter.common.exception.ZidanApiException;
import java.util.UUID;

/**
 * @Author jiguiquan
 * @Email jiguiquan@haier.com
 * @Data 2023-06-30 13:59
 */
public class MyJsScriptEngine {
    private static final ObjectMapper mapper = new ObjectMapper();
    private final JsInvokeService sandboxService;
    private final UUID scriptId;

    public MyJsScriptEngine(JsInvokeService jsInvokeService, String script) {
        this.sandboxService = jsInvokeService;
        try {
            this.scriptId = this.sandboxService.eval(script);
        } catch (Exception e) {
            throw ZidanApiException.create("500", "js eval exception", "js脚本编译异常");
        }
    }

    public Object invoke(Integer a, Integer b) {
        try {
            return sandboxService.invokeFunction(scriptId, a, b);
        } catch (Exception e) {
            throw ZidanApiException.create("500", "js invoke exception", "js脚本执行异常");
        }
    }
}
